package com.zrc.japktool.apk.xapk2apk;

import com.google.gson.Gson;
import com.zrc.japktool.apk.zipalignsign.Apk4kAligner;
import com.zrc.japktool.apk.zipalignsign.zipalign.ZipAlign;
import com.zrc.japktool.util.FileUtil;
import com.zrc.japktool.util.TaskLog;
import com.zrc.japktool.apk.zipalignsign.ApkSign;
import com.zrc.japktool.util.Zip4jUtil;

import java.io.File;
import java.nio.file.Paths;

public class XApk2Apk {
    private TaskLog log = null;

    public XApk2Apk(TaskLog log) {
        this.log = log;
    }

    public void xapk2apk(String inXapkPath, String outApkDirPath) {
        try {
            log.tip("xapk转apk: " + "开始");
            //第1步:从xapk中读取manifest.json中json数据
            String gsonStr = Zip4jUtil.readStr(inXapkPath, "manifest.json");
            ManifestGsonBean manifestGsonBean = new Gson().fromJson(gsonStr, ManifestGsonBean.class);

            //第2步:从xapk中读取提取base.apk和split.apk
            log.info("xapk转apk: " + "提取base.apk,split.apk ...");
            String xapkNamme = new File(inXapkPath).getName().replace(".xapk", "").replace("\\", "/");
            File workDirPath = new File(new File(outApkDirPath), xapkNamme);//工作目录，用于缓存
            String outApkNamme = xapkNamme + ".apk";
            String outApkPath = new File(outApkDirPath, outApkNamme).getAbsolutePath().replace("\\", "/");

            if (!workDirPath.exists()) {
                workDirPath.mkdirs();
            }

            String baseApkName = "";
            for (ManifestGsonBean.SplitApksBean splitApk : manifestGsonBean.getSplit_apks()) {
                if (splitApk.getId().equals("base")) {
                    baseApkName = splitApk.getFile();
                }
                Zip4jUtil.extractFile(inXapkPath, splitApk.getFile(), workDirPath.getAbsolutePath());
            }

            for (ManifestGsonBean.SplitApksBean splitApk : manifestGsonBean.getSplit_apks()) {
                if (!splitApk.getId().equals("base")) {
                    Zip4jUtil.extractDir(workDirPath.getPath() + "/" + splitApk.getFile(), "lib/", workDirPath.getPath());
                }
            }

            //第3步:将split.apk的资源放入base.apk中
            log.info("xapk转apk: " + "正在合并资源...");
            Zip4jUtil.addDir(workDirPath.getPath() + "/" + baseApkName, workDirPath.getPath() + "/lib", "lib/");

            new File(workDirPath.getPath() + "/" + baseApkName).renameTo(new File(outApkPath));

            //第4步:修改base.apk中AndroidManifest.xml
            log.info("xapk转apk: " + "正在合并AndroidManifest.xml...");
            ManifestXmlUtil.modifiyApkManifestXml(outApkPath);
            log.info("xapk转apk: " + "清除缓存中...");
            if (workDirPath.exists()) {
                FileUtil.delDir(workDirPath);
            }
            log.info("xapk转apk: " + "结束");

            //第5步: 对齐
            String apkNamme = new File(outApkPath).getName().replace(".apk", "").replace("\\", "/");
            String ziplan_inApkPath = outApkPath;
            File ziplan_inApFile = new File(ziplan_inApkPath);
            File ziplan_outApkFile = new File(outApkDirPath, apkNamme + "-zipalign.apk");
            String ziplan_outApkPath = ziplan_outApkFile.getAbsolutePath().replace("\\", "/");
            Apk4kAligner apk4kAligner = new Apk4kAligner(log);
            apk4kAligner.zipAlign(ziplan_inApkPath, ziplan_outApkPath, false);
            //ZipAlign.zipAlign(ziplan_inApkPath, ziplan_outApkPath,log);

            //第6步: 签名
            String sign_inApkPath = ziplan_outApkPath;
            String sign_outApkPath = new File(outApkDirPath, apkNamme + "-zipalign-sign.apk").getAbsolutePath();
            ApkSign apkSign = new ApkSign(log);
            apkSign.sign("android", "androiddebugkey", "android", false, Paths.get(sign_inApkPath), Paths.get(sign_outApkPath));
//            if (ziplan_inApFile.exists()) {
//                ziplan_inApFile.delete();
//                log.info("apk签名: " + "清理xapk转apk的缓存...");
//            }
            if (ziplan_outApkFile.exists()) {
                ziplan_outApkFile.delete();
                log.info("apk签名: " + "清理apk对齐缓存...");
            }
            FileUtil.deleteFileWithRetry(ziplan_inApkPath);
            FileUtil.deleteFileWithRetry(ziplan_outApkPath);
            log.tip("xapk转apk: " + "结束");
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String inXapkPath = "C:/Users/Administrator/Desktop/xapk/demo1.xapk";
        String outApkPath = "C:/Users/Administrator/Desktop/xapk/";
        XApk2Apk xApk2Apk = new XApk2Apk(TaskLog.newTaskLog());
        xApk2Apk.xapk2apk(inXapkPath, outApkPath);
    }

}
